﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Hosting;

namespace Web.Common
{
    public class BaseWebApiExt
    {
        public static Dictionary<string, string> DicToken = new Dictionary<string, string>();
        public static Dictionary<string, string> StaffDicToken = new Dictionary<string, string>();


        static string Pass1 = "P@ssw0rd";
        static string Pass2 = "P@ssw0rd";


        /// <summary>
        /// 获取用户新的token--同时更新静态变量  和 数据库
        /// </summary>
        /// <returns></returns>
        public static string GetNewToken(int UserID)
        {
            //LoginModel userData = WealthPool.BLL.Users.GetLoginModel(userId);

            byte[] idByte = BitConverter.GetBytes(UserID);
            //byte[] nameByte = BitConverter.GetBytes(long.Parse(userData.LoginName));
            byte[] tokenArray = Encoding.Default.GetBytes(Guid.NewGuid().ToString());

            int len = idByte.Length + tokenArray.Length; //+ nameByte.Length
            byte[] array = new byte[len];

            Array.Copy(idByte, 0, array, 0, idByte.Length);
            Array.Copy(tokenArray, 0, array, idByte.Length, tokenArray.Length);
            //Array.Copy(nameByte, 0, array, idByte.Length, nameByte.Length);
            //Array.Copy(tokenArray, 0, array, idByte.Length + nameByte.Length, tokenArray.Length);

            var newtoken = Convert.ToBase64String(array);


            //字典是否存在
            if (DicToken == null)
            {
                DicToken = new Dictionary<string, string>();
            }

            if (DicToken.Where(d => d.Key == UserID.ToString()).Count() > 0)
            {
                DicToken[UserID.ToString()] = newtoken; //替换
            }
            else
            {
                DicToken.Add(UserID.ToString(), newtoken);//加载
            }

            FreeADO.DBUtility.DbHelperSQL.ExecuteSql("update Users set Token='" + newtoken + "' where ID=" + UserID);//更新库

            return newtoken;
        }


        /// <summary>
        /// 获取用户真实的token--解密DES
        /// </summary>
        /// <returns></returns>
        public static string GetRealityToken(string token)
        {

            byte[] inputByteArray = Convert.FromBase64String(token);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Key = ASCIIEncoding.ASCII.GetBytes(Pass1);
                des.IV = ASCIIEncoding.ASCII.GetBytes(Pass2);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }

        /// <summary>
        /// 获取用户加密的token--加密DES
        /// </summary>
        /// <returns></returns>
        public static string ToCiphertextToken(string token)
        {

            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                byte[] inputByteArray = Encoding.UTF8.GetBytes(token);
                des.Key = ASCIIEncoding.ASCII.GetBytes(Pass1);
                des.IV = ASCIIEncoding.ASCII.GetBytes(Pass2);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Convert.ToBase64String(ms.ToArray());
                ms.Close();
                return str;
            }
        }

        /// <summary>
        /// 解析Token获取UserID
        /// </summary>
        /// <returns></returns>
        public static int GetUserIDByToken()
        {
            string tokenStr = HttpContext.Current.Request.Headers["Token"];//获取Token

            tokenStr = GetRealityToken(tokenStr);//解密Token

            MemoryStream ms = new MemoryStream(Convert.FromBase64String(tokenStr));
            byte[] bt = ms.ToArray();
            int nId = BitConverter.ToInt32(bt, 0);//获得UserID

            return nId;
        }


        /// <summary>
        /// 转换星期
        /// </summary>
        /// <param name="DayOfWeek"></param>
        /// <returns></returns>
        public static string Week(DayOfWeek DayOfWeek)
        {
            string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            string week = weekdays[Convert.ToInt32(DayOfWeek)];

            return week;
        }


        /// <summary>
        /// 获取项目文件根目录
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetMapPath(string path)
        {
            var phicyPath = HostingEnvironment.MapPath(path);

            return phicyPath;
        }

        /// <summary>
        /// 读取指定文件
        /// </summary>
        /// <param name="path"></param>
        public static string Read(string path)
        {
            try
            {
                StreamReader sr = new StreamReader(path, Encoding.Default);
                return sr.ReadToEnd();
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
                return "";
            }
        }
    }
}